/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedBean;

import Merlion.CRM.entity.CustomerEntity;
import Merlion.CRM.entity.CustomerExecutiveEntity;
import Merlion.CRM.bean.SalesLeadModuleRemote;
import Merlion.userManagement.entity.SystemUserEntity;
import Merlion.util.state.ClientState;
import Merlion.util.helper.ClientsAnalysis;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import org.primefaces.component.chart.series.ChartSeries;
import org.primefaces.event.RowEditEvent;
import org.primefaces.model.chart.CartesianChartModel;

@ManagedBean(name = "SalesLeadManagedBean")
@ViewScoped
public class SalesLeadManagedBean implements Serializable {

    //ADD SALES LEAD DATA
    /*private String id;
    private String salutation;
    private String firstName;
    private String lastName;
    private String name;
    private String industry;
    private double annualRevenue;
    private int    numOfEmployees;
    private String mobileNum;
    private String faxNum;
    private String website;
    private double rating;
    private String address;
    private String addressState;
    private String contactNum;
    private String country;
    private String city;
    private String postalCode;
    private String emailAddress;
    private String businessType;
    private String leadSource;
    private String description;
    private String title;
    private String department;
    private Date   dob;
    private String companyRegId;*/
    private ClientState newSalesLead = new ClientState();
    private ClientState selectedSalesLead;
    private ClientState[] selectedSalesLeads;
    private Long selectedId;
    private Long custEx;
    private List<SystemUserEntity> custExList;
    private SystemUserEntity custExecutive = new SystemUserEntity();
    private boolean editMode;
    private List<ClientState> sales;
    private ClientState selectedViewSalesLead;
    private List<ClientsAnalysis> leadList;
    private CartesianChartModel model = new CartesianChartModel();
    private String message;
    private boolean duplicate;
    private boolean qualified = true;
    private String convertMessage;
    private boolean editMode2;
    private List<ClientState> convertedLeads;
    @EJB
    private SalesLeadModuleRemote smb;

    /** Creates a new instance of salesLeadsManagedBean */
    public SalesLeadManagedBean() {
    }

    public CartesianChartModel getModel() {
        ChartSeries leads = new ChartSeries();
        leads.setLabel("Leads");
        int count = 0;
        for (int i = 0; i <= 12; i++) {
            count = smb.countLeads(i);
            String mis = getMonthInString(i);
            leads.set(mis, count);
        }
        return model;
    }

    public boolean isEditMode2() {
        return editMode2;
    }

    public void setEditMode2(boolean editMode2) {
        this.editMode2 = editMode2;
    }

    public boolean isQualified() {

        String qualifiedString = (String) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("qualified");
        if (qualifiedString.equals("true")) {
            qualified = true;
        } else if (qualifiedString.equals("false")) {
            qualified = false;
        }
        return qualified;
    }

    public void setQualified(boolean qualified) {
        this.qualified = qualified;
    }

    public ClientState getNewSalesLead() {
        return newSalesLead;
    }

    public void setNewSalesLead(ClientState newSalesLead) {
        this.newSalesLead = newSalesLead;
    }

    public String getMonthInString(int month) {
        String monthInString = "";

        if (month == 1) {
            monthInString = "Jan";
        } else if (month == 2) {
            monthInString = "Feb";
        } else if (month == 3) {
            monthInString = "Mar";
        } else if (month == 4) {
            monthInString = "Apr";
        } else if (month == 5) {
            monthInString = "May";
        } else if (month == 6) {
            monthInString = "Jun";
        } else if (month == 7) {
            monthInString = "Jul";
        } else if (month == 8) {
            monthInString = "Aug";
        } else if (month == 9) {
            monthInString = "Sep";
        } else if (month == 10) {
            monthInString = "Oct";
        } else if (month == 11) {
            monthInString = "Nov";
        } else if (month == 12) {
            monthInString = "Dec";
        }

        return monthInString;

    }

    public void setModel(CartesianChartModel model) {
        this.model = model;
    }

    public List<ClientsAnalysis> getLeadList() {
        if (leadList == null) {
            leadList = smb.getLeadList();
        }
        return leadList;
    }

    public void setLeadList(List<ClientsAnalysis> leadList) {
        this.leadList = leadList;
    }

    public void convertInitView(PhaseEvent event) {
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        if (convertedLeads == null) {
            convertedLeads = smb.viewConvertedLeads();
        }
    }

    public List<ClientState> getConvertedLeads() {
        return convertedLeads;
    }

    public void setConvertedLeads(List<ClientState> convertedLeads) {
        this.convertedLeads = convertedLeads;
    }

    public void initView(PhaseEvent event) {
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        if (sales == null) {
            sales = smb.viewSalesLeads();
        }
    }

    public String getConvertMessage() {
        if (convertMessage == null) {
            convertMessage = (String) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("convertMessage");
        }
        return convertMessage;
    }

    public void setConvertMessage(String convertMessage) {
        this.convertMessage = convertMessage;
    }

    public String getMessage() {
        if (message == null) {
            message = (String) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("message");
        }
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public boolean isDuplicate() {
        String dupString = (String) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("duplicate");
        if (dupString.equals("true")) {
            duplicate = true;
        } else if (dupString.equals("false")) {
            duplicate = false;
        }

        return duplicate;
    }

    public void setDuplicate(boolean duplicate) {
        this.duplicate = duplicate;
    }

    public boolean isEditMode() {
        return editMode;
    }

    public void setEditMode(boolean editMode) {
        this.editMode = editMode;
    }

    public ClientState getSelectedViewSalesLead() {
        return selectedViewSalesLead;
    }

    public void setSelectedViewSalesLead(ClientState selectedViewSalesLead) {
        System.out.println(":::WEB::: Set SelectedViewSalesLead");
        this.selectedViewSalesLead = selectedViewSalesLead;
    }

    public ClientState getSelectedSalesLead() {
        return selectedSalesLead;
    }

    public void setSelectedSalesLead(ClientState selectedSalesLead) {
        System.out.println(":::WEB::: SET SELECTED SALES LEAD");
        this.selectedSalesLead = selectedSalesLead;

    }

    public List<SystemUserEntity> getCustExList() {
        return smb.getAllCustomerExecutives();
    }

    public void setCustExList(List< SystemUserEntity> custExList) {
        this.custExList = custExList;
    }

    public void onEditRow(RowEditEvent event) {


        System.out.println(":::WEB::: On Edit Row");
        ClientState eClient = (ClientState) event.getObject();

        if (eClient != null) {
            System.out.println(":::WEB::: Edited client not null");
            String eSalutation = eClient.getSalutation();
            String eFirstName = eClient.getFirstName();
            String eLastName = eClient.getLastName();
            String eName = eClient.getName();
            String eIndustry = eClient.getIndustry();
            double eAnnualRev = eClient.getAnnualRevenue();
            int eNumOfEmployees = eClient.getNumOfEmployees();
            String eMobileNum = eClient.getMobileNum();
            String eFaxNum = eClient.getFaxNum();
            String eWebsite = eClient.getWebsite();
            double eRating = eClient.getRating();
            String eAddress = eClient.getAddress();
            String eContact = eClient.getContactNum();
            String eCountry = eClient.getCountry();
            String eCity = eClient.getCity();
            String ePostalCode = eClient.getPostalCode();
            String eEmailAddress = eClient.getEmailAddress();
            String eType = eClient.getBusinessType();
            String eStatus = eClient.getStatus();
            String eLeadSource = eClient.getLeadSource();
            String eDescription = eClient.getDescription();
            String eTitle = eClient.getTitle();
            String eDepartment = eClient.getDepartment();
            Date eDob = eClient.getDob();
            String eAddressState = eClient.getAddressState();

            Long clientId = eClient.getId();

            System.out.println(":::WEB::: Calling Edit Sales Lead");
            smb.editSalesLead(clientId, eSalutation, eFirstName, eLastName, eName, eIndustry, eAnnualRev,
                    eNumOfEmployees, eContact, eMobileNum, eFaxNum, eWebsite,
                    eRating, eAddress, eAddressState, eCountry, eCity,
                    ePostalCode, eEmailAddress, eType, eStatus, eLeadSource,
                    eTitle, eDepartment, eDob, eDescription);
        }

    }

    public void addSalesLead(ActionEvent event) {
        System.out.println(":::WEB::: Add sales lead");


        String salutation = newSalesLead.getSalutation();
        String firstName = newSalesLead.getFirstName();
        String lastName = newSalesLead.getLastName();
        String name = newSalesLead.getName();
        String industry = newSalesLead.getIndustry();
        double annualRev = newSalesLead.getAnnualRevenue();
        int numOfEmployees = newSalesLead.getNumOfEmployees();
        String mobileNum = newSalesLead.getMobileNum();
        String faxNum = newSalesLead.getFaxNum();
        String website = newSalesLead.getWebsite();
        double rating = newSalesLead.getRating();
        String address = newSalesLead.getAddress();
        String contact = newSalesLead.getContactNum();
        String country = newSalesLead.getCountry();
        String city = newSalesLead.getCity();
        String postalCode = newSalesLead.getPostalCode();
        String emailAddress = newSalesLead.getEmailAddress();
        String type = newSalesLead.getBusinessType();
        String status = newSalesLead.getStatus();
        String leadSource = newSalesLead.getLeadSource();
        String description = newSalesLead.getDescription();
        String title = newSalesLead.getTitle();
        String department = newSalesLead.getDepartment();
        Date dob = newSalesLead.getDob();
        String addressState = newSalesLead.getAddressState();
        String companyRegId = newSalesLead.getCompanyRegId();

        Long salesLeadID = smb.addSalesLead(salutation, firstName, lastName, name, companyRegId,
                industry, annualRev, numOfEmployees,
                contact, mobileNum, faxNum, website, rating,
                address, addressState, country, city, postalCode,
                emailAddress, type, leadSource, title, department, dob, description);
        System.out.println(":::WEB::: Sales Lead ID is: " + salesLeadID);

        if (salesLeadID != 0) {
            String successMessage = "\t\t\tYou have sucessfully added a new sales lead!";
            setDuplicate(false);
            setMessage(successMessage);
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("duplicate", "false");
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("message", successMessage);
        } else {
            setDuplicate(true);
            String failMessage = "\t\t\tDuplicate lead data found in the database!" + "\n"
                    + "\t\t\tSales lead is not added to the system.";
            setMessage(failMessage);
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("duplicate", "true");
            FacesContext.getCurrentInstance().getExternalContext().getFlash().put("message", failMessage);
        }

        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("createNewSalesLeadStatus.xhtml");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void delete(ActionEvent event) {

        System.out.println(":::WEB::: Delete Sales Lead");
        if (selectedSalesLead != null) {
            System.out.println(":::WEB::: Selected sales lead is not null");
            Long salesLeadId = selectedSalesLead.getId();
            System.out.println(":::WEB::: Sales Lead ID Is :" + salesLeadId);
            smb.deleteSalesLead(salesLeadId);
            System.out.println(":::WEB::: Deletion done");
        } else {
            System.out.println(":::WEB::: Selected sales lead is null");
        }

        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("salesLeads.xhtml");
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

    public void convertSalesLead(ActionEvent event) {
        Long returnId = Long.parseLong("1");

        if (selectedViewSalesLead.getStatus().equals("Qualified")) {
            System.out.println("Convert sales lead");
            Long leadId = selectedViewSalesLead.getId();
            returnId = smb.convertSalesLead(leadId);
            System.out.println("Return id " + returnId);

            if (returnId == 0) {
                System.out.println("Duplicate found!");
                FacesContext context = FacesContext.getCurrentInstance();

                context.addMessage(null, new FacesMessage("Lead Conversion not successful!", "Duplicate found in the database. This lead is converted to contact."));

            } else if (returnId == 2) {
                System.out.println("Duplicate contact found!");
                FacesContext context = FacesContext.getCurrentInstance();

                context.addMessage(null, new FacesMessage("Lead Conversion not successful!", "Duplicate customer found in the database. Duplicate contact found in the database." + "\n"
                        + "This lead will not be converted to either customer or contact account."));

            } else {
                try {
                    FacesContext.getCurrentInstance().getExternalContext().redirect("salesLeads.xhtml");
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }

        } else {
            System.out.println("Status not qualified!");
            FacesContext context = FacesContext.getCurrentInstance();

            context.addMessage(null, new FacesMessage("Lead Conversion not successful!", "Status has not been qualified"));

        }



    }

    public void addInfo() {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Sample info message", "PrimeFaces rocks!"));
    }

    public List<ClientState> getSales() {
 
        return this.sales;
    }

    public ClientState[] getSelectedSalesLeads() {
        return selectedSalesLeads;
    }

    public void setSelectedSalesLeads(ClientState[] selectedSalesLeads) {
        this.selectedSalesLeads = selectedSalesLeads;
    }

    public void deleteSalesLeads() {
        System.out.println(":::WEB::: Delete Sales Leads");

        if (selectedSalesLeads != null) {
            System.out.println(":::WEB::: If selected sales leads not null");
            for (int i = 0; i < selectedSalesLeads.length; i++) {
                System.out.println("selectedSalesLeads i: " + i + " - " + selectedSalesLeads[i].getId());
                smb.deleteSalesLead(selectedSalesLeads[i].getId());
            }
        } else {
            System.out.println(":::WEB::: Selected sales leads are null");
        }

        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("salesLeads.xhtml");
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

    public void cancelDelete() {
        for (ClientState client : selectedSalesLeads) {
            client = null;
        }
        if (selectedSalesLeads == null) {
            System.out.println(":::WEB::: Deletion of sales leads cancelled");
        } else {
            System.out.println(":::WEB::: Deletion of sales leads are not cancelled");
        }

    }

    public void save(ActionEvent event) {
        System.out.println(":::WEB::: Save Edit Sales Lead");

        Long salesLeadId = selectedViewSalesLead.getId();
        String cSalutation = selectedViewSalesLead.getSalutation();
        String cFirstName = selectedViewSalesLead.getFirstName();
        String cLastName = selectedViewSalesLead.getLastName();
        String cName = selectedViewSalesLead.getName();
        String cIndustry = selectedViewSalesLead.getIndustry();
        double cAnnualRev = selectedViewSalesLead.getAnnualRevenue();
        int cNumOfEmployees = selectedViewSalesLead.getNumOfEmployees();
        String cMobileNum = selectedViewSalesLead.getMobileNum();
        String cFaxNum = selectedViewSalesLead.getFaxNum();
        String cWebsite = selectedViewSalesLead.getWebsite();
        double cRating = selectedViewSalesLead.getRating();
        String cContactNumber = selectedViewSalesLead.getContactNum();
        String cAddress = selectedViewSalesLead.getAddress();
        String cCountry = selectedViewSalesLead.getCountry();
        String cCity = selectedViewSalesLead.getCity();
        String cPostalCode = selectedViewSalesLead.getPostalCode();
        String cEmailAddress = selectedViewSalesLead.getEmailAddress();
        String cBusinessType = selectedViewSalesLead.getBusinessType();
        String cStatus = selectedViewSalesLead.getStatus();
        String cLeadSource = selectedViewSalesLead.getLeadSource();
        String cDescription = selectedViewSalesLead.getDescription();
        String cAddressState = selectedViewSalesLead.getAddressState();
        String cTitle = selectedViewSalesLead.getTitle();
        String cDepartment = selectedViewSalesLead.getDepartment();
        Date cDob = selectedViewSalesLead.getDob();

        System.out.println("Client ID is :" + salesLeadId + ".Client Name : " + cName);
        System.out.println(":::WEB::: Calling edit salesLead");
        smb.editSalesLead(salesLeadId, cSalutation, cFirstName, cLastName, cName,
                cIndustry, cAnnualRev, cNumOfEmployees,
                cContactNumber, cMobileNum, cFaxNum, cWebsite, cRating,
                cAddress, cAddressState, cCountry, cCity, cPostalCode, cEmailAddress,
                cBusinessType, cStatus, cLeadSource,
                cTitle, cDepartment, cDob, cDescription);
        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("salesLeads.xhtml");
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }
}
